package main

import (
	"flag"
	"fmt"
	"go-zero-example/cmd/userrpc/internal/util"
	"os"

	"go-zero-example/cmd/userrpc/internal/config"
	"go-zero-example/cmd/userrpc/internal/server"
	"go-zero-example/cmd/userrpc/internal/svc"
	"go-zero-example/cmd/userrpc/pb/userrpc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

var configFile = flag.String("f", "etc/userrpc.yaml", "the config file")

func main() {

	// 数据库初始化连接
	dir, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	path := dir + "/config.json"
	// 实例化配置文件
	_ = util.ReadJson(path)
	// 实例化数据库
	_, err = util.GetOrmEngine()
	if err != nil {
		panic(err)
	}

	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		userrpc.RegisterUserServiceServer(grpcServer, server.NewUserServiceServer(ctx))

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
